package com.chenfan.mcn.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chenfan.common.vo.UserVO;
import com.chenfan.mcn.config.UserVoContextHolder;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * Entity属性自动填充  配合@TableField(.. fill = FieldFill.INSERT) ,@TableField(.. fill = FieldFill.UPDATE) 使用
 * 注意：fieldName, fieldType 必须与entity中的属性名、类型对应上，如果无此属性，则填充默认忽略
 *      如果Mapper中自定义DML-SQL的，必须加@Param(Constants.ENTITY)
 * McnMetaObjectHandler 不满足实际需求，自动填充功能由MybatisPlusConfig.BaseEntityFillInnerInterceptor实现
 * @author wulg
 * @date 2021-07-08
 **/
@Deprecated
public class McnMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserVO userVO = UserVoContextHolder.getUserVo();
        if(userVO != null) {
            this.strictInsertFill(metaObject, "createBy", () -> userVO.getUserId(), Long.class);
            this.strictInsertFill(metaObject, "createName", () -> userVO.getRealName(), String.class);
            this.strictInsertFill(metaObject, "updateBy", () -> userVO.getUserId(), Long.class);
            this.strictInsertFill(metaObject, "updateName", () -> userVO.getRealName(), String.class);
            this.strictInsertFill(metaObject, "departmentId", () -> userVO.getDepartmentId(), Long.class);
            this.strictInsertFill(metaObject, "companyId", () -> userVO.getCompanyId(), Long.class);
            this.strictInsertFill(metaObject, "tenantId", () -> userVO.getTenantId(), Long.class);
        }
        Date now = new Date();
        this.strictInsertFill(metaObject, "createDate", () -> now, Date.class);
        this.strictInsertFill(metaObject, "updateDate", () -> now, Date.class);
        //兼容 红人那块 后期同一替换
        this.strictInsertFill(metaObject, "isDelete", () -> 0, Integer.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //注解则是指定该属性在对应情况下必有值,如果无值则入库会是null
        //建议获取不到userVO信息，更新的公共字段必须赋值，没有则自动填充入库会是null ，针对定时任务/回调等非用户直接操作
        /** 注意：定制InnerInterceptor->beforeUpdate 处理 并去掉基类对应的 @TableField(.. fill = FieldFill.UPDATE) */
        UserVO userVO = UserVoContextHolder.getUserVo();
        if(userVO != null) {
            this.strictUpdateFill(metaObject, "updateBy", () -> userVO.getUserId(), Long.class);
            this.strictUpdateFill(metaObject, "updateName", () -> userVO.getRealName(), String.class);
            //兼容 红人那块 后期同一替换
            this.strictInsertFill(metaObject, "modifyBy", () -> userVO.getUserId(), Long.class);
            this.strictInsertFill(metaObject, "modifyName", () -> userVO.getRealName(), String.class);
        }
        Date now = new Date();
        this.strictInsertFill(metaObject, "updateDate", () -> now, Date.class);
    }
}
